/**
* @version v 0.2.0 2009/10/19
* @package Nerv Widgets, nw.js
* @subpackage Nerv Window, window.js
* @author Manuele Castellan <manuele.castellan@gmail.com>
*
* @copyright    Copyright (C) Copyright (c) 2009 Manuele Castellan. All rights reserved.
* @license        GNU/GPLv3, see LICENSE
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*/

NW3.Window = function(params){
	// creo oggetto
	var oWindow = {
		el : document.createElement('div'),
		icon : null,
		title : '',
		statusText : '',
		
		width : 300,
		height : 250,
		
		minwidth : '130',
		minheight : '50',
		
		top : null,
		right : null,
		bottom : null,
		left : null,
		
		resize : false,
		
		classprefix : 'tWindowMaker',
		
		contents : new Array(),
		
		ajaxUrl : null,
		
		buttonclose : null,
		buttonhelp : null,
		
		buttonresize : null,
		statusbarobjects : new Array(),
		
		dragstatus : null,
		drageffect : null,
		onDrag : null,
		onDragEnd : null
		
		//containerTitle : this.barTop,	// barra alta della finestra
		//containerStatus : this.statusBar	// barra di stato
	};
	
	// corpo finestra
	oWindow.oContainer = document.createElement('div');
	oWindow.oContents = document.createElement('div');
	
	/* 
	 * crea barra per finestra
	 */
	createWinBar = function(){
		var oText = document.createElement('span');
		var oTitle = document.createElement('div');
		var boxTitle = document.createElement('div');
		var containerTitle = document.createElement('div');
		// bottoni
		var oButtons = document.createElement('div');
		//var oButtonClose = document.createElement('span');
		//var oButtonHelp = document.createElement('span');
		var boxTitleClose = document.createElement('div');
		
		// icona
		var oIcon = document.createElement('img');
		
		// creo title temp
		/*var oTextTemp = document.createElement('span');
		oTextTemp.style.visibility = 'hidden';*/
		
		var oWinBar = {
			classprefix : null,
			icon : null,		// src image
			text : '',
			buttons : null,
			
			otext : oText,
			otitle : oTitle,
			oboxtitle : boxTitle,
			oboxtitleclose : boxTitleClose,
			ocontainer : containerTitle,
			obuttons : oButtons,
			oicon : oIcon
		};
		
		/* setta il testo per la barra */
		oWinBar.setText = function(val){
			oWinBar.otext.innerHTML = val;
			
			oWinBar.text = val;
			
			//oTextTemp.innerHTML = oWinBar.getText();
			//oText.innerHTML = oTextTemp.innerHTML;
		};
		
		/* recupera il testo della barra */
		oWinBar.getText = function(){
			return oWinBar.otext.innerHTML;
		};
		
		/* setta icona */
		oWinBar.setIcon = function(val){
			oWinBar.icon = val;
			oWinBar.oicon.src = oWinBar.icon;
		};
		
		
		/* add button */
		oWinBar.addButton = function(obj){
			oWinBar.obuttons.appendChild(obj.output());
			
			oWinBar.buttons = oWinBar.obuttons;
		};
		
		
		
		/* output */
		oWinBar.output = function(){
			oWinBar.oboxtitleclose.style.clear = 'both';
			
			// collego gli oggetti tra di loro
			oWinBar.otitle.appendChild(oWinBar.otext);
			oWinBar.oboxtitle.appendChild(oWinBar.otitle);
			oWinBar.oboxtitle.appendChild(oWinBar.obuttons);
			oWinBar.oboxtitle.appendChild(oWinBar.oboxtitleclose);
			oWinBar.ocontainer.appendChild(oWinBar.oboxtitle);
			
			// setto icona
			if(oWinBar.icon){
				oWinBar.otext.parentNode.insertBefore(oWinBar.oicon, oWinBar.otext);
			}
			oWinBar.setClasses();
			
			return oWinBar.ocontainer;
		};
		
		/*
		 * resize oText
		 * ---
		 * sistema euristico
		 */
		oWinBar.resizeTitle = function(){
			// ripristino testo iniziale
			oWinBar.otext.innerHTML = oWinBar.text;
			var text_temp = oWinBar.text;
			
			// limito i carateri fino a che gli oggetti non sono tutti con stesso valore di top
			for(e=0;e<=10;e++){
				icon_top = NW3.core.object.getPosTop(oWinBar.oicon);
				text_top = NW3.core.object.getPosTop(oWinBar.otext);
				buttons_top = NW3.core.object.getPosTop(oWinBar.obuttons);
				
				if(icon_top == 0) icon_top = text_top;
				else if(buttons_top == 0) icon_top = text_top;
				
				container_height = oWinBar.ocontainer.offsetHeight;
				
				// confronto valore top degli oggetti
				if( (text_top > icon_top ) || 
					(buttons_top > text_top) || 
					(oWinBar.container_height < container_height)){
					
					text_temp = text_temp + '...';
					limit = text_temp.length - 10;
					
					text_temp = text_temp.substring(0, limit);
					oWinBar.otext.innerHTML = text_temp + '...';
				}
				else break;
			}
		};
		
		// setta classi
		oWinBar.setClass = function(val){
			oWinBar.classprefix = val;
		};
		
		/* setta le classi per l'output */
		oWinBar.setClasses = function(){
			oWinBar.otext.className = oWinBar.classprefix + 'Title';
			oWinBar.otitle.className = oWinBar.classprefix + 'Titlecx';
			oWinBar.oboxtitle.className = oWinBar.classprefix + 'Titlesx';
			oWinBar.ocontainer.className = oWinBar.classprefix + 'Titledx';
			
			if(oWinBar.icon) oWinBar.oicon.className = oWinBar.classprefix + 'Img';
			oWinBar.obuttons.className = oWinBar.classprefix + 'Buttons';
		};
		
		return oWinBar;
	};
	
	
	/* barra top */
	oWindow.containerTitle = new createWinBar();
	/* barra di stato */
	oWindow.containerStatus = new createWinBar();
	
	oWindow.el.style.position = 'absolute';
	
	/* button Close */
	oWindow.setButtonClose = function(f){
		var bClose = new NW3.form.Button();
		bClose.setClass('tWindowMakerButtonClose');
		bClose.setTitle(NW3.lang.Close);
		
		bClose.onClick(function(){
			if(f != undefined) f();
			oWindow.hide();
		});
		
		oWindow.buttonclose = bClose;
	};
	
	
	/* button Help */
	oWindow.setButtonHelp = function(f){
		var bHelp = new NW3.form.Button();
		bHelp.setClass('tWindowMakerButtonHelp');
		bHelp.setTitle(NW3.lang.Help);
		
		bHelp.onClick(function(){
			if(f != undefined) f();
		});
		
		oWindow.buttonhelp = bHelp;
	};
	
	
	/** add external button */
	oWindow.addButton = function(obj){
		oWindow.containerTitle.addButton(obj);
	};
	
	// show window
	oWindow.show = function(){
		if(oWindow.resize) oWindow.containerTitle.resizeTitle();
		//oWindow.containerStatus.resizeTitle();
		oWindow.el.style.visibility = 'visible';
	};
	
	// hide window
	oWindow.hide = function(){
		oWindow.el.style.visibility = 'hidden';
	};
	
	/** move horizotal/vertical obj of distance pixel */
	oWindow.move = function(distance, direction, speed){
		var obj = {
			distance : distance,
			speed : 5,
			direction : 'H',
			difference : 10
		};
		
		if(direction){
			switch(direction.toUpperCase()){
				case 'H':
				case 'HORIZONTAL':
				case 'Y':
					obj.direction = 'H';
				case 'V':
				case 'VERTICAL':
				case 'X':
					obj.direction = 'V';
			}
		}
		
		if(obj.direction == 'H'){
			obj.difference = obj.speed * obj.difference;
			obj.start = parseInt(oWindow.getLeft());
			obj.position = obj.start + obj.distance;
			if(obj.start == 0) obj.position = obj.distance;
			
			if(NW3.core.string.isNumeric(speed)) obj.speed = speed;
			
			moveObj = function(){
				if(obj.speed > 0){
					if(obj.direction) left = parseInt(oWindow.getLeft());
					
					//if(obj.distance > 0){
						posLeft = left + obj.difference;
						if(posLeft == 0) posLeft = obj.difference;
						if(posLeft > obj.position) posLeft = obj.position;
						
						oWindow.setLeft(posLeft + 'px');
						
						if(posLeft != obj.position) setTimeout('moveObj()', obj.speed);
					/*}
					else if(obj.distance < 0){
						obj.difference = parseInt('-' + obj.difference);
						posLeft = left + obj.difference;
						if(posLeft == 0) posLeft = obj.difference;
						if(posLeft > obj.position) posLeft = obj.position;
						
						oWindow.setLeft(posLeft + 'px');
						
						if(posLeft != obj.position) setTimeout('moveObj()', obj.speed);
					}*/
				}
				else{
					oWindow.setTop(obj.position + 'px');
				}
			};
		}
		else{
			obj.difference = obj.speed * obj.difference;
			obj.start = parseInt(oWindow.getTop());
			obj.position = obj.start + obj.distance;
			if(obj.start == 0) obj.position = obj.distance;
			
			if(NW3.core.string.isNumeric(speed)) obj.speed = speed;
			
			moveObj = function(){
				if(obj.speed > 0){
					if(obj.direction) n_top = parseInt(oWindow.getTop());
					
					//if(obj.distance > 0){
						posTop = n_top + obj.difference;
						if(posTop == 0) posTop = obj.difference;
						if(posTop > obj.position) posTop = obj.position;
						
						oWindow.setTop(posTop + 'px');
						
						if(posTop != obj.position) setTimeout('moveObj()', obj.speed);
					/*}
					else if(obj.distance < 0){
						obj.difference = parseInt('-' + obj.difference);
						posLeft = left + obj.difference;
						if(posLeft == 0) posLeft = obj.difference;
						if(posLeft > obj.position) posLeft = obj.position;
						
						oWindow.setLeft(posLeft + 'px');
						
						if(posLeft != obj.position) setTimeout('moveObj()', obj.speed);
					}*/
				}
				else{
					oWindow.setTop(obj.position + 'px');
				}
			};
		}
		
		moveObj(obj);
	};
	
	// set title
	oWindow.setTitle = function(val){
		oWindow.title = val;
		oWindow.containerTitle.setText(oWindow.title);
	};
	
	// set status text
	oWindow.setStatusText = function(val){
		oWindow.statusText = val;
		oWindow.containerStatus.setText(val);
	};
	
	
	// set icon
	oWindow.setIcon = function(url){
		oWindow.icon = url;
		
		oWindow.containerTitle.setIcon(oWindow.icon);
	};
	
	
	
	// set width
	oWindow.setWidth = function(val){
		if(val) oWindow.width = parseInt(val);
		oWindow.el.style.width = oWindow.width;
	};
	
	// set height
	oWindow.setHeight = function(val){
		if(val) oWindow.height = parseInt(val);
		oWindow.el.style.height = oWindow.height;
	};
	
	// set top
	oWindow.setTop = function(val){
		if(val) oWindow.top = val;
		oWindow.el.style.top = oWindow.top;
	};
	
	// set right
	oWindow.setRight = function(val){
		if(val) oWindow.right = val;
		oWindow.el.style.right = oWindow.right;
	};
	
	// set left
	oWindow.setLeft = function(val){
		if(val) oWindow.left = val;
		oWindow.el.style.left = oWindow.left;
	};
	
	// set bottom
	oWindow.setBottom = function(val){
		if(val) oWindow.bottom = val;
		oWindow.el.style.bottom = oWindow.bottom;
	};
	
	// get width
	oWindow.getWidth = function(val){
		return oWindow.width;
	};
	
	// get height
	oWindow.getHeight = function(val){
		return oWindow.height;
	};
	
	// get top
	oWindow.getTop = function(){
		return oWindow.top;
	};
	
	// get right
	oWindow.getRight = function(){
		return oWindow.right;
	};
	
	// get left
	oWindow.getLeft = function(){
		return oWindow.left;
	};
	
	// get bottom
	oWindow.getBottom = function(){
		return oWindow.bottom;
	};
	
	// set class
	oWindow.setClass = function(val){
		oWindow.classprefix = val;
	};
	
	// add contents
	oWindow.add = function(oNode){
		oWindow.contents.push(oNode);
	};
	
	// add contents from url with Ajax
	oWindow.loadAjaxUrl = function(ajaxUrl){
		if(ajaxUrl) oWindow.ajaxUrl = ajaxUrl;
		
		if(oWindow.ajaxUrl){
			oAjax = new NW3.ajax.Request(oWindow.ajaxUrl, {
				method : 'GET',
				onComplete : function(response){
					oWindow.oContents.innerHTML = response.responseText;
				}
			});
		}
	};
	
	// add nwobjects to status bar
	oWindow.addNwObjStatusBar = function(oObj){
		oWindow.statusbarobjects.push(oObj);
	};
	
	// statusbar
	// set button resize
	oWindow.setStatusbarButtonResize = function(){
		// window resizable
		var bResize = new NW3.form.Button();
		bResize.setClass('tWindowMakerStatusbarButtonResize');
		bResize.setTitle(NW3.lang.Resize);
		
		// eventi su window
		//var oMouseEvents = new NW3.event.Handling(document.body);
		
		bResize.onMouseUp(function(id, o, ev){
			if(oWindow.resize) {
				// setto evento mousemove
				document.onmousemove = function(evt){
					return false;
				};
			}
		});
		
		
		bResize.onMouseDown(function(id, o, ev){
			var startMposX = NW3.client.mouseX(ev);
			var startMposY = NW3.client.mouseY(ev);
			
			w_actual = oWindow.el.style.width;
			h_actual = oWindow.el.style.height;
			
			// setto evento mousemove
			document.onmousemove = function(evt){
				oWindow.evt = evt;
				
				w_diff = parseInt(NW3.client.mouseX(evt)) - startMposX;
				h_diff = parseInt(NW3.client.mouseY(evt)) - startMposY;
				
				w = parseInt(w_actual) + w_diff;
				h = parseInt(h_actual) + h_diff;
				
				// setto valori minimi di resize
				if(oWindow.minwidth  >= w) w = oWindow.minwidth;
				if(oWindow.minheight >= h) h = oWindow.minheight;
				
				oWindow.el.style.width  = w + 'px';
				oWindow.el.style.height = h + 'px';
				
				// ricalcolo lunghezza titolo e status bar
				oWindow.containerTitle.resizeTitle();
				//oWindow.containerStatus.resizeTitle();
			};
		});
		
		return bResize;
	};
	
	oWindow.setResizable = function(val){
		if(val){
			if(oWindow.width && oWindow.height) oWindow.buttonresize = oWindow.setStatusbarButtonResize();
			oWindow.resize = true;
		}
		else oWindow.resize = false;
	};
	
	// setta classi
	oWindow.setClass = function(val){
		if(val) oWindow.classprefix = val;
		oWindow.el.className = oWindow.classprefix;
		
		oWindow.oContainer.className = oWindow.classprefix + 'Box';
		if(oWindow.resize) oWindow.oContainer.style.height = '100%';
	};
	
	/** enable | disable drag */
	oWindow.setDraggable = function(val){
		if(val) oWindow.dragstatus = val;
	};
	
	/* attiva opacity al drag */
	oWindow.setDragEffect = function(options){
		if(options){
			oWindow.drageffect = options;
		}
	};
	
	// output window object
	oWindow.output = function(){
		// barra titolo
		oWindow.containerTitle.setClass(oWindow.classprefix);
		
		containerTitleHtml = oWindow.containerTitle.output();
		oWindow.el.appendChild(containerTitleHtml);
		
		// corpo finestra
		oWindow.oContainer.appendChild(oWindow.oContents);
		oWindow.el.appendChild(oWindow.oContainer);
		
		// status bar
		oWindow.containerStatus.setClass(oWindow.classprefix + 'Statusbar');
		oWindow.containerStatus.setText(oWindow.statusText);
		oWindow.el.appendChild(oWindow.containerStatus.output());
		
		// aggiungo bottoni title bar
		if(oWindow.buttonhelp) oWindow.containerTitle.addButton(oWindow.buttonhelp);
		if(oWindow.buttonclose) oWindow.containerTitle.addButton(oWindow.buttonclose);
		// aggiungo bottoni status bar
		if(oWindow.buttonresize) oWindow.containerStatus.addButton(oWindow.buttonresize);
		for(i=0; oWindow.statusbarobjects.length>i; i++){
			oWindow.containerStatus.addButton(oWindow.statusbarobjects[i]);
		}
		
		// aggiungo contenuti alla finestra
		for(oc=0;oWindow.contents.length>oc;oc++){
			if(!NW3.core.object.isObject(oWindow.contents[oc])){
				oWindow.oContents.innerHTML = ((oWindow.oContents.innerHtml != undefined) ? oWindow.oContents.innerHtml : '') + oWindow.contents[oc];
			}
			else oWindow.oContents.appendChild(oWindow.contents[oc]);
		}
		
		
		// se non ci sono riferimenti di posizione centro la finestra
		if(oWindow.width && oWindow.height){
			if(!oWindow.top) {
				if(document.all) doc_height = document.body.offsetHeight;
				else doc_height = window.innerHeight;
				TopPosition = (doc_height) ? (doc_height - oWindow.height)/2 : 0;
				oWindow.top     = TopPosition;
			}
			if(!oWindow.left) {
				if(document.all) doc_width = document.body.offsetWidth;
				else doc_width = window.innerWidth;
				LeftPosition = (doc_width) ? (doc_width - oWindow.width)/2 : 0;
				oWindow.left     = LeftPosition;
			}
		}
		
		// dimensioni e posizione
		if(oWindow.width) oWindow.el.style.width = oWindow.width + 'px';
		if(oWindow.height) oWindow.el.style.height = oWindow.height + 'px';
		if(oWindow.bottom) oWindow.el.style.bottom = oWindow.bottom + 'px';
		if(oWindow.left) oWindow.el.style.left = oWindow.left + 'px';
		if(oWindow.right) oWindow.el.style.right = oWindow.right + 'px';
		if(oWindow.top) oWindow.el.style.top = oWindow.top + 'px';

		// setto classe
		oWindow.setClass();
		
		// setto z-index
		if(NW3.core.NW_window_zIndex){
			oWindow.el.style.zIndex = NW3.core.NW_window_zIndex;
		}
		else{
			NW3.core.NW_window_zIndex = '100';
			oWindow.el.style.zIndex = NW3.core.NW_window_zIndex;
		}
		
		// setto z-index al clicck sulla finestra
		//var oWindowEvent = new NW3.event.Handling(oWindow.el);
		NW3.event.addEvent(oWindow.el, "mousedown", function(){
			if(NW3.core.NW_window_zIndex){
				NW3.core.NW_window_zIndex = parseInt(NW3.core.NW_window_zIndex) + 3;
				oWindow.el.style.zIndex = NW3.core.NW_window_zIndex + 3;
			}
		});
		
		// setto drag
		if(oWindow.dragstatus){
			var oDrag = new NW3.event.Drag(oWindow.el, containerTitleHtml);
			
			oDrag.setOnChangePosition(function(){
				oWindow.top = oDrag.getTop();
				oWindow.left = oDrag.getLeft();
			});
			
			if(oWindow.onDrag){
				oDrag.setOnDrag(oWindow.onDrag);
			}
			
			if(oWindow.onDragEnd){
				oDrag.setOnDragEnd(oWindow.onDragEnd);
			}
			
			// drag opacity effect
			if(oWindow.drageffect){
				if(oWindow.drageffect.effect == 'opacity'){
					NW3.event.addEvent(containerTitleHtml, "mousedown", function(ev){
						NW3.rendering.setOpacity(oWindow.el, oWindow.drageffect.value);
					});
					NW3.event.addEvent(containerTitleHtml, 'mouseup', function(){
						NW3.rendering.setOpacity(oWindow.el, 100);
					});
				}
			}
		}
		
		oWindow.hide();
		
		return oWindow.el;
	};
	
	oWindow.print = function(){
		NW3.core.object.print(oWindow.output());
	};
	
	oWindow.replace = function(targetElement){
		NW3.core.object.replace(targetElement, oWindow.output());
	};
	
	oWindow.insertAfter = function(targetElement){
		NW3.core.object.insertAfter(oWindow.output(), targetElement);
	};
	
	oWindow.insertBefore = function(targetElement){
		NW3.core.object.insertBefore(oWindow.output(), targetElement);
	};
	
	oWindow.appendChild = function(targetElement){
		NW3.core.object.appendChild(oWindow.output(), targetElement);
	};
	
	// set params
	if(params){
		oWindow.setTitle(params.title);
		oWindow.setWidth(params.width);
		oWindow.setHeight(params.height);
		
		oWindow.setTop(params.top);
		oWindow.setBottom(params.bottom);
		oWindow.setLeft(params.left);
		oWindow.setRight(params.right);
		
		oWindow.setIcon(params.icon);
		oWindow.setStatusText(params.status);
		oWindow.setDraggable(params.draggable);
		oWindow.setResizable(params.resizable);
		oWindow.setButtonClose(params.buttonClose);
		oWindow.setButtonHelp(params.buttonHelp);
		
		if(params.ajaxUrl) oWindow.loadAjaxUrl(params.ajaxUrl);
	}
	
	return oWindow;
};